<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\Response;

class Goods extends Base
{
    /*访问的首页列表*/
    public function index()
    {
        $title = "商品列表";

        $data = \app\admin\model\Goods::select();

        return view('/goods/index',[
            'title' => $title,
            'data' => $data
        ]);
    }

    // 添加权限
    public function add()
    {
        $title = "添加商品";

        // 获取第一次分类数据
        $cateone = \app\admin\model\Category::where("pid",0)->select();

        // 获取商品类型
        $type = \app\admin\model\Type::select();

        return view('/goods/add',[
            'title' => $title,
            'cateone' => $cateone,
            'type' => $type
        ]);
    }

    // 添加方法
    public function insert(Request $request)
    {
        // 获取所有的数据
        $data = $request->param();

        //自定义函数，过滤富文本编辑器，单独进行过滤处理
        $data['goods_body'] = $request->param('goods_body','','trim');

        // 表单验证
        $rule = [
            'goods_name|商品名称' => 'require|token',
            'goods_price|商品价格' => 'require|number|gt:0',
            'goods_number|商品数量' => 'require|number|gt:0',
            'cate_id|分类id' => 'require|number',
            'type_id|类型id' => 'require|number'
        ];

        $validate = new \think\Validate($rule);

        if(!$validate->check($data)){
            $error = $validate->getError();
            $this->error($error);
            die;
        }

        // 单独获取logo数据
        $data['goods_logo'] = $this->upload_logo();

        // 添加到数据库中
        $goods = \app\admin\model\Goods::create($data,true);

        // 多图片上传
        $this->upload_pics($goods->id);

        // 属性添加
        $attr_value = $data['attr_value'];

        $goods_attr = [];
        foreach($attr_value as $k=>$v)
        {
            foreach($v as $value)
            {
                $row = [
                    'goods_id' => $goods->id,
                    'attr_id' => $k,
                    'attr_value' => $value
                ];

                $goods_attr[] = $row;
            }
        }

        $obj_attr = new \app\admin\model\GoodsAttr();

        $obj_attr->saveAll($goods_attr);

        $this->success("添加成功",'admin/goods/index');
    }

    // 更改方法
    public function edit(int $id)
    {
        if(empty($id)){
            $this->error("参数错误",'admin/goods/index');
            die;
        }
        $title = "商品修改方法";

        // 商品的原始基本信息
        $goods = \app\admin\model\Goods::find($id);

        // 获取当前三级分类id
        $crte_three = \app\admin\model\Category::find($goods['cate_id']);

        // 获取当前二级的分类id
        $crte_two = \app\admin\model\Category::find($crte_three['pid']);

        // 获取所有的一级分类
        $crte_one = \app\admin\model\Category::where('pid',0)->select();

        // 获取所有的二级分类
        $crte_two_all = \app\admin\model\Category::where('pid',$crte_two['pid'])->select();

        // 获取所有的三级分类
        $crte_three_all = \app\admin\model\Category::where('pid',$crte_two['id'])->select();

        // 获取所有图片
        $goods_pics = \app\admin\model\GoodsPics::where('goods_id',$id)->select();

        // 获取商品类型
        $type = \app\admin\model\Type::select();

        // 获取所有的商品属性
        $attr = \app\admin\model\Attribute::where('type_id',$goods['type_id'])->select();

        foreach($attr as &$v){

            $v = $v->getData();
            $v['attr_values'] = explode(',',$v['attr_values']);
        }

        unset($v);

        // 获取当前商品所有的商品属性
        $goods_attr = \app\admin\model\GoodsAttr::where('goods_id',$id)->select();

        $new_list = [];
        foreach($goods_attr as $k=>$v)
        {
            $new_list[$v['attr_id']][] = $v['attr_value'];

        }

        return view('/goods/edit',[
            'title' => $title,
            'goods' => $goods,
            'crte_two' => $crte_two,
            'crte_three' => $crte_three,
            'crte_one' => $crte_one,
            'crte_two_all' => $crte_two_all,
            'crte_three_all' => $crte_three_all,
            'type' => $type,
            'attr' => $attr,
            'new_list' => $new_list,
            'goods_pics' => $goods_pics
        ]);

    }

    // 更新方法
    public function update(Request $request)
    {

        $data = $request->param();

        //自定义函数，过滤富文本编辑器，单独进行过滤处理
        $data['goods_body'] = $request->param('goods_body','','trim');

        // 参数检测
        $rule = [
            'goods_name|商品名称' => "require|token",
            'goods_price|商品价格' => 'require|number|gt:0',
            'goods_number|商品数量' => 'require|number|gt:0',
            'cate_id|商品分类' => 'require|number'
        ];

        $validate = new \think\Validate($rule);

        if(!$validate->check($data))
        {
            return $this->error($validate->getError());
            die;
        }

        // logo 更新
        $file = $request->file('goods_logo');
        if(!empty($file)){
            $data['goods_logo'] = $this->upload_logo();
        }

        // 修改数据库中的方法
        \app\admin\model\Goods::update($data,['id'=>$data['id']],true);

        // 继续上传相册图片
        $this->upload_pics($data['id']);

        // 删除商品原来属性值
        \app\admin\model\GoodsAttr::where("Goods_id",$data['id'])->delete();

        // 重新添加商品属性值
        $attr_value = $data['attr_value'];

        $goods_attr = [];
        foreach($attr_value as $k=>$v)
        {
            foreach($v as $value)
            {
                $row = [
                    'goods_id' => $data['id'],
                    'attr_id' => $k,
                    'attr_value' => $value
                ];

                $goods_attr[] = $row;
            }
        }

        $obj_attr = new \app\admin\model\GoodsAttr();

        // saveAll方法如果数据库中有这个字段会更新没有会创建。
        $obj_attr->saveAll($goods_attr);

        // 修改成功
        $this->success("修改成功",'admin/goods/index');

    }

    // 多图片上传
    private function upload_pics($goods_id)
    {
        $files = request()->file('goods_pics');

        // 定义空变量 接受数组
        $goods_pics = [];

        foreach($files as $file)
        {

            // 添加文件移动到对应目录
            $info = $file->validate(['ext'=>'jpg,png,jpeg,gif'])->move(ROOT_PATH . 'public' . DS . "upload" . DS . 'goodspics');

            if($info){

                // 生成文件目录
                $res = DS . 'upload' . DS . 'goodspics'. DS . $info->getSaveName();

                // 生成的缩略图大文件
                $pics_big = DS . 'upload' . DS . 'goodspics' . DS . date('Ymd') .  DS . 'thumb_800_' . $info->getFilename();

                // 分割成数组
                $temp = explode(DS,$info->getSaveName());

                // 生成的缩略图小文件
                $pics_small =  DS . 'upload' . DS . 'goodspics' . DS . $temp[0] . DS . 'thumb_400_' . $temp[1];

                // 生成缩略图 重新保存
                $image = \think\Image::open('.'.$res);

                // 进行缩略  重新保存
                $image->thumb(800,800)->save('.'.$pics_big);
                $image->thumb(400,400)->save('.'.$pics_small);

                // 组装成一条数据
                $row = [
                    'goods_id' => $goods_id,
                    'pics_big' => $pics_big,
                    'pics_small' => $pics_small
                ];

                $goods_pics[] = $row;

            }else{

                $this->error($file->getError());
            }

            $obj = new \app\admin\model\GoodsPics();

            $obj->saveAll($goods_pics);
        }
    }

    // 删除多图片上传
    public function picsdel(int $id)
    {
        if(empty($id)){
            $res = [
                'code' => 10001,
                'msg' => "参数错误"
            ];

            return json(res);
        }

        \app\admin\model\GoodsPics::destroy($id);

        $res = [
            "code" => 10000,
            'msg' => "删除成功"
        ];
        return json($res);

    }

    // 三级联动
    public function getTree(int $id)
    {
        if(empty($id)){
            $msg = [
                'code' => 10001,
                'msg' => "参数错误"
            ];
            return json($msg);
        }
        // 获取所有的数据
        $data = \app\admin\model\Category::where('pid',$id)->select();

        $msg = [
            'code' => 10000,
            'msg' => "参数成功",
            'data' => $data
        ];
        return json($msg);
    }

    // 商品logo
    private function upload_logo(){

        // 获取图片地址
        $file = request()->file("goods_logo");

        if($file){
            // 移动位置
            $info = $file->validate(['ext'=>"jpg,png,jpeg,gif"])->move(ROOT_PATH . 'public' . DS ."upload" . DS . "logo");

            // 如果成功
            if($info){

                $res = DS . 'upload' . DS . 'logo' . DS . $info->getSaveName();

                return $res;
            }else{
                $error = $file->getError();
                $this->error($error);
            }
        }
    }

    // 删除商品
    public function delete(int $id)
    {
        if(empty($id))
        {
            $this->error("参数错误",'admin/Goods/index');
            die;
        }

        \app\admin\model\GoodsAttr::where('goods_id',$id)->delete();
        \app\admin\model\GoodsPics::where('goods_id',$id)->delete();
        \app\admin\model\Goods::destroy($id);


        $this->success("删除成功","admin/Goods/index");
    }
}
